<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="知识点" prop="knowledgePointName">
        <el-input
          v-model="queryParams.knowledgePointName"
          placeholder="请输入知识点名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="章节名称" prop="chapterName">
        <el-input
          v-model="queryParams.chapterName"
          placeholder="请输入章节名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['know:points:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="pointsList"
      row-key="knowledgePointId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
<!--      <el-table-column label="父知识点id" prop="parentId" />-->
      <el-table-column label="知识点名称" align="center" prop="knowledgePointName" />
<!--      <el-table-column label="描述" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <div v-html="scope.row.description"></div>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="所属章节" align="center" prop="courseChapters.chapterName" />
      <el-table-column label="是否有ppt" align="center" prop="pptUrl" :formatter="formatYesNo">
      </el-table-column>
      <el-table-column label="是否有短视频" align="center" prop="videoUrl" :formatter="formatYesNo">
      </el-table-column>
      <el-table-column label="是否有练习题目" align="center" prop="practiceUrl" :formatter="formatYesNo">
      </el-table-column>
      <el-table-column label="是否公开" align="center" prop="isVisibility" :formatter="formatYesNo">
      </el-table-column>
      <el-table-column label="点赞人数" align="center" prop="likesNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['know:points:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['know:points:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['know:points:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-chat-dot-round"
            @click="showCommentDialog(scope.row)"
          >查看评论</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="showNoteDialog(scope.row)"
          >查看笔记</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 评论查看弹窗 -->
    <el-dialog
      title="评论详情"
      :visible.sync="commentDialogVisible"
      width="800px"
      append-to-body>
      <div v-loading="commentLoading">
        <!-- 使用之前实现的评论组件 -->
        <comment-list :comments="commentTree" :post-id="pkId" :commentType="1" @refresh-comments="loadComments" />
      </div>

      <span slot="footer" class="dialog-footer">
    <el-button @click="commentDialogVisible = false">关 闭</el-button>
  </span>
    </el-dialog>
    <!-- 笔记列表弹窗 -->
    <el-dialog
      :visible.sync="noteDialogVisible"
      title="笔记列表"
      width="60%"
    >

      <note-index :knowledgePointId="currentKnowledgePointId" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="noteDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加或修改知识点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="父知识点id" prop="parentId">
          <treeselect v-model="form.parentId" :options="pointsOptions" :normalizer="normalizer" placeholder="请选择父知识点id" />
        </el-form-item>
        <el-form-item label="知识点名称" prop="knowledgePointName">
          <el-input v-model="form.knowledgePointName" placeholder="请输入知识点名称" />
        </el-form-item>
        <el-form-item label="描述">
          <editor v-model="form.description" :min-height="192"/>
        </el-form-item>
        <el-form-item label="所属章节" prop="courseChapters.chapterId">
          <el-select v-model="form.courseChapters.chapterId" placeholder="请选择章节">
            <el-option v-for="chapter in chapters" :key="chapter.chapterId" :label="chapter.chapterName" :value="chapter.chapterId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="pdf">
          <el-button size="small" type="primary" @click="openUploadDialog('pdf')">点击上传文件</el-button>
          <!-- 添加预览按钮 -->
          <el-button v-if="form.pptUrl" size="small" type="info" @click="previewFile('pdf')">预览</el-button>
          <!-- 修改pdf下载按钮 -->
          <el-button v-if="form.pptUrl" size="small" type="warning" @click="downloadFile('pdf')">下载</el-button>
          <!-- 清空pdf对应的Url  -->
          <el-button v-if="form.pptUrl" size="small" type="danger" @click="deleteFile('pdf')">删除</el-button>
        </el-form-item>
        <el-form-item label="video">
          <el-button size="small" type="primary" @click="openUploadDialog('video')">点击上传文件</el-button>
          <!-- 添加预览按钮 -->
          <el-button v-if="form.videoUrl" size="small" type="info" @click="previewFile('video')">预览</el-button>
          <!-- 修改video下载按钮 -->
          <el-button v-if="form.videoUrl" size="small" type="warning" @click="downloadFile('video')">下载</el-button>
          <!-- 清空pdf对应的Url  -->
          <el-button v-if="form.videoUrl" size="small" type="danger" @click="deleteFile('video')">删除</el-button>
        </el-form-item>
        <el-form-item label="练习题目">
          <el-button size="small" type="primary" @click="openUploadDialog('practice')">点击上传文件</el-button>
          <!-- 添加预览按钮 -->
          <el-button v-if="form.practiceUrl" size="small" type="info" @click="previewFile('practice')">预览</el-button>
          <!-- 修改practice下载按钮 -->
          <el-button v-if="form.practiceUrl" size="small" type="warning" @click="downloadFile('practice')">下载</el-button>
          <!-- 清空practice对应的Url  -->
          <el-button v-if="form.practiceUrl" size="small" type="danger" @click="deleteFile('practice')">删除</el-button>
        </el-form-item>
        <el-form-item label="是否公开" prop="isVisibility">
          <el-switch
            v-model="form.isVisibility"
            active-value="1"
            inactive-value="0"
            active-text="是"
            inactive-text="否"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传文件弹窗 -->
    <el-dialog :title="'上传 ' + currentUploadType + ' 文件'" :visible.sync="uploadDialogVisible" width="500px">
      <el-upload
        class="upload-demo"
        action="/dev-api/common/upload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :file-list="uploadFileList"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <DialogPage :fileData="previewData" :show="previewPageOpen" @closeDialog="closePreview" :title="previewData.fileName" width="60%"/>
  </div>
</template>

<script>
import {listPoints, getPoints, delPoints, addPoints, updatePoints, clearPointsUrl} from "@/api/know/points";
import { getAll } from "@/api/know/courseChapters";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import DialogPage from "@/views/know/preview/DialogPage.vue";
import CommentList from "@/components/Comment/CommentList.vue";
import {commentTree} from "@/api/know/comments";
import NoteIndex from '@/views/know/notes/index.vue';

export default {
  name: "Points",
  components: {
    CommentList,
    Treeselect,
    DialogPage,
    NoteIndex
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 知识点表格数据
      pointsList: [],
      chapters:[],
      // 知识点树选项
      pointsOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      uploadDialogVisible: false,
      currentUploadType: '',
      uploadFileList: [],
      fileListDialogVisible: false,
      currentFileListType: '',
      currentFileList: [],
      // 查询参数
      queryParams: {
        knowledgePointName: null,
        chapterName: null,
        isHavePpt: null,
        isHaveVideo: null,
        isHavePractice: null,
      },
      // 表单参数
      form: {
        courseChapters:{
          chapterId:null,
          chapterName: null
        }
      },
      commentDialogVisible: false,  // 评论弹窗显示状态
      currentPost: null,            // 当前查看的帖子
      commentTree: [],              // 评论树数据
      commentLoading: false,         // 评论加载状态
      pkId:"",
      noteDialogVisible: false,
      currentNotes: [],
      currentKnowledgePointId:null,
      // 表单校验
      rules: {
        knowledgePointName: [
          { required: true, message: "知识点名称不能为空", trigger: "blur" }
        ],
        "courseChapters.chapterId": [
          { required: true, message: "章节不能为空", trigger: "blur" }
        ],
      },
      previewPageOpen:false,
      previewData:{
        fileName: '',
        type: '', //  文件类型
        url:'',
      }
    };
  },
  created() {
    this.getList();
    this.getCoursesList();
  },
  methods: {
    downloadFile(fileType) {
      let fileUrl = '';
      let fileName = '';

      // 根据文件类型获取对应的URL
      switch (fileType) {
        case 'pdf':
          fileUrl = this.form.pptUrl;
          break;
        case 'video':
          fileUrl = this.form.videoUrl;
          break;
        case 'practice':
          fileUrl = this.form.practiceUrl;
          break;
        default:
          this.$message.error('未知文件类型');
          return;
      }

      if (!fileUrl) {
        this.$message.warning('文件不存在');
        return;
      }

      // 提取文件名（带后缀）
      fileName = fileUrl.split('/').pop();

      // 创建隐藏的a标签进行下载
      const link = document.createElement('a');
      link.href = fileUrl;
      link.download = decodeURIComponent(fileName); // 解码中文文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // 兼容性处理：如果浏览器不支持download属性
      if (typeof link.download === 'undefined') {
        window.open(fileUrl);
      }
    },
    deleteFile(operateType){
      let fileType = '';
      let fileKey = '';
      switch (operateType) {
        case 'pdf':
          fileType = 1;
          fileKey = 'pptUrl';
          break;
        case 'video':
          fileType = 2;
          fileKey = 'videoUrl';
          break;
        case 'practice':
          fileType = 3;
          fileKey = 'practiceUrl';
          break;
      }
      this.$confirm(`确定要删除${operateType}文件吗？`, '提示',{
        type: 'warning'
      })
        .then(() => {
          clearPointsUrl(fileType,this.form.knowledgePointId).then(res=>{
            if(res.code === 200){
              this.$message.success('删除'+ fileType +'成功');
              this.getList();
              this.form[fileKey] = null;
            }else{
              this.$message.error('删除'+ fileType +'失败');
            }
          })
        })
    },
    async showNoteDialog(row) {
      this.noteDialogVisible = true;
      this.currentKnowledgePointId = row.knowledgePointId
    },
    // 显示评论弹窗
    async showCommentDialog(row) {
      this.currentPost = row;
      this.commentDialogVisible = true
      this.pkId = row.knowledgePointId
      try {
        this.commentLoading = true
        commentTree({infoId:row.knowledgePointId,commentType:1}).then(response => {
          this.commentTree  = response.data
          this.loading = false;
        });
      } catch (e) {
        console.error('获取评论失败:', e)
        this.$message.error('评论加载失败')
      } finally {
        this.commentLoading = false
      }
    },
    loadComments(){
      commentTree({infoId:this.pkId,commentType:1}).then(response => {
        this.commentTree  = response.data
        this.loading = false;
      });
    },
    previewFile(fileExtension) {
      let previewUrl = '';
      let preViewType = '';
      console.log("form =>",this.form);
      switch (fileExtension){
        case 'pdf':
          preViewType = 'pdf';
          previewUrl = this.form.pptUrl;
          this.previewData.type = preViewType;
          this.previewData.url = previewUrl;
          break;
        case 'excel':
          preViewType = 'excel';
          previewUrl = this.form.videoUrl;
          this.previewData.type = preViewType;
          this.previewData.url = previewUrl;
          break;
        case 'practice':
        case 'docx':
          preViewType = 'word';
          previewUrl = this.form.practiceUrl;
          this.previewData.type = preViewType;
          this.previewData.url = previewUrl;
          break;
        case 'video':
          preViewType = 'video';
          previewUrl = this.form.videoUrl;
          this.previewData.type = preViewType;
          this.previewData.url = previewUrl;
          break;
        default:
          this.$message.warning('暂不支持该文件格式的预览');
          return;
      }
      //  统一处理文件名称
      this.previewData.fileName = this.getFileName(previewUrl)
      this.previewPageOpen = true;
    },
    closePreview() {
      this.previewPageOpen = false;
      this.previewData = {
        type: '', //  文件类型
        url:''
      }

    },
    openUploadDialog(type) {
      this.currentUploadType = type;
      this.uploadDialogVisible = true;
    },
    handleUploadSuccess(response, file, fileList) {
      console.log(`${this.currentUploadType} 文件上传成功`, response);
      if (this.currentUploadType === 'pdf') {
        this.form.pptUrl = response.url;
      } else if (this.currentUploadType === 'video') {
        this.form.videoUrl = response.url;
      } else if (this.currentUploadType === 'practice') {
        this.form.practiceUrl = response.url;
      }
      this.uploadFileList = null;
    },
    handleUploadError(err, file, fileList) {
      console.error(`${this.currentUploadType} 文件上传失败`, err);
    },
    beforeUpload(file) {
      // 上传前的校验逻辑，比如文件类型、大小等
      const isAllowedType = true; // 根据实际需求修改
      const isAllowedSize = true; // 根据实际需求修改
      if (!isAllowedType) {
        this.$message.error('不支持的文件类型');
      }
      if (!isAllowedSize) {
        this.$message.error('文件大小超出限制');
      }
      return isAllowedType && isAllowedSize;
    },
    getFileName(name) {
      if (name) {
        let resName = '';
        const parts = name.split('/');
        if (parts.length > 1) {
          resName = parts[parts.length - 1]
          if (resName.indexOf('.') > -1) {
            resName = resName.substring(0, resName.lastIndexOf('.'));
          }
          return resName;
        }
      }
      return name;
    },
    /** 查询知识点列表 */
    getList() {
      this.loading = true;
      listPoints(this.queryParams).then(response => {
        this.pointsList = this.handleTree(response.data, "knowledgePointId", "parentId");
        this.loading = false;
      });
    },
    formatYesNo(row, column, cellValue) {
      return cellValue === "" || cellValue==null || cellValue=== 0  ? '否' : '是';
    },
    getCoursesList(){
      this.loading = true;
      getAll().then(response => {
        this.chapters = response.data;
        this.loading = false;
      });

    },
    /** 转换知识点数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.knowledgePointId,
        label: node.knowledgePointName,
        children: node.children
      };
    },
    /** 查询知识点下拉树结构 */
    getTreeselect() {
      listPoints().then(response => {
        this.pointsOptions = [];
        const data = { knowledgePointId: 0, knowledgePointName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "knowledgePointId", "parentId");
        this.pointsOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        knowledgePointId: null,
        parentId: null,
        knowledgePointName: null,
        description: null,
        courseChapters:{
          chapterId:null,
          chapterName: null
        },
        isHavePpt: null,
        isHaveVideo: null,
        isHavePractice: null,
        isVisibility: null,
        isValid: null,
        createdBy: null,
        createdAt: null,
        updateBy: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.knowledgePointId) {
        this.form.parentId = row.knowledgePointId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加知识点";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.parentId;
      }
      getPoints(row.knowledgePointId).then(response => {
        this.form = response.data;
        this.form.isVisibility = String(row.isVisibility)
        this.open = true;
        this.title = "修改知识点";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.knowledgePointId != null) {
            updatePoints(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPoints(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除知识点编号为"' + row.knowledgePointId + '"的数据项？').then(function() {
        return delPoints(row.knowledgePointId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  },
};
</script>
